<template>
  <div class="addGoods">
    <div class="breadcrumb">
      <el-breadcrumb separator-class="el-icon-arrow-right">
        <el-breadcrumb-item :to="{ path: '/' }">首页</el-breadcrumb-item>
        <el-breadcrumb-item>商品管理</el-breadcrumb-item>
        <el-breadcrumb-item :to="{ path: '/goods' }">商品列表</el-breadcrumb-item>
        <el-breadcrumb-item>添加商品</el-breadcrumb-item>
      </el-breadcrumb>
    </div>

    <!-- 内容卡片区 -->
    <el-card class="box-card content">
      <!-- title -->
      <el-alert title="添加商品信息" type="info" center show-icon :closable="false"></el-alert>

      <!-- 进度条 -->
      <el-steps
        :space="200"
        :active="activeName | toNumber"
        align-center
        process-status="finish"
        finish-status="success"
      >
        <el-step title="基本信息"></el-step>
        <el-step title="商品参数"></el-step>
        <el-step title="商品属性"></el-step>
        <el-step title="商品图片"></el-step>
        <el-step title="商品内容"></el-step>
        <el-step title="完成"></el-step>
      </el-steps>
      <div class="addGoodsContent">
        <el-form
          :model="addgoodsForm"
          :rules="addgoodsRules"
          ref="addgoodsRef"
          label-position="top"
          label-width="100px"
        >
          <!-- 左侧导航 -->
          <el-tabs
            tab-position="left"
            v-model="activeName"
            @tab-click="handleClick"
            :before-leave="beforeToleave"
          >
            <!-- 第一项 -->
            <el-tab-pane label="基本信息" name="0">
              <el-form-item label="商品分类" prop="goods_cat">
                <el-cascader
                  v-model="selectCateKey"
                  :options="GoodsCategories"
                  :props="cateProps"
                  @change="handleChange"
                ></el-cascader>
              </el-form-item>
              <el-form-item label="商品名称" prop="goods_name">
                <el-input v-model="addgoodsForm.goods_name"></el-input>
              </el-form-item>
              <el-form-item label="商品价格" prop="goods_price">
                <el-input type="number" v-model="addgoodsForm.goods_price"></el-input>
              </el-form-item>
              <el-form-item label="商品重量" prop="goods_weight">
                <el-input type="number" v-model="addgoodsForm.goods_weight"></el-input>
              </el-form-item>
              <el-form-item label="商品数量" prop="goods_number">
                <el-input type="number" v-model="addgoodsForm.goods_number"></el-input>
              </el-form-item>
            </el-tab-pane>

            <!-- 动态参数列表====参数 -->
            <el-tab-pane label="商品参数" name="1">
              <el-form-item
                v-for="item in manyTableData"
                :key="item.attr_id"
                :label="item.attr_name"
              >
                <el-checkbox-group v-model="item.attr_vals">
                  <el-checkbox v-for="(v,i) in item.attr_vals" :key="i" :label="v"></el-checkbox>
                </el-checkbox-group>
              </el-form-item>
            </el-tab-pane>

            <!-- 静态属性列表===属性 -->
            <el-tab-pane label="商品属性" name="2">
              <!-- ======= -->
              <el-form-item
                v-for="item in onlyTableData"
                :key="item.attr_id"
                :label="item.attr_name"
              >
                <el-checkbox-group v-model="item.attr_vals">
                  <el-checkbox v-for="(v,i) in item.attr_vals" :key="i" :label="v"></el-checkbox>
                </el-checkbox-group>
              </el-form-item>
            </el-tab-pane>

            <!-- 上传图片 -->
            <el-tab-pane label="商品图片" name="3">
              <el-upload
                action="http://www.klxin.cn:8888/api/private/v1/upload"
                :on-preview="handlePreview"
                :on-remove="handleRemove"
                :on-success="handlesuccess"
                list-type="picture"
                :headers="headerObj"
              >
                <el-button size="small" type="primary">点击上传</el-button>
              </el-upload>
            </el-tab-pane>
            <el-tab-pane label="商品内容" name="4">
              <!-- 富文本编辑器组件 -->
              <quill-editor v-model="addgoodsForm.goods_introduce"></quill-editor>
              <!-- 添加商品按钮 -->
              <el-button type="primary" class="btnAdd" @click="addGoods">添加商品</el-button>
            </el-tab-pane>
          </el-tabs>
        </el-form>

        <!-- 预览图片对话框 -->
        <el-dialog
          title="图片预览"
          @close="closepreviewVisible"
          :visible.sync="previewVisible"
          width="50%"
        >
          <img :src="previewPath" class="previewImg" />
        </el-dialog>
      </div>
    </el-card>
  </div>
</template>
           
<script>
export default {
  name: "addgoods",
  data() {
    return {
      // 进度条的位置
      activeName: "0",
      // 输入数据
      addgoodsForm: {
        goods_name: "",
        goods_price: "",
        goods_number: "",
        goods_weight: "",
        goods_cat: "",
        // 上传的图片组
        uplaedPic: [],
        //商品的详情介绍
        goods_introduce: ""
      },
      // 数据检验规则
      addgoodsRules: {
        goods_name: [
          { required: true, message: "请输入商品名称", trigger: "blur" }
        ],
        goods_price: [
          { required: true, message: "请输入商品价格", trigger: "blur" }
        ],
        goods_number: [
          { required: true, message: "请输入商品数量", trigger: "blur" }
        ],
        goods_weight: [
          { required: true, message: "请输入商品重量", trigger: "blur" }
        ],
        goods_cat: [
          { required: true, message: "请选择商品参数", trigger: "change" }
        ]
      },
      // 商品分类===渲染联级选择器
      GoodsCategories: [],
      // 商品分类--选项配置
      cateProps: {
        expandTrigger: "hover",
        value: "cat_id",
        label: "cat_name",
        children: "children"
      },
      // 选择的商品分类===id值==数组
      selectCateKey: [],
      //动态参数列表====参数
      manyTableData: [],
      //静态属性列表===属性
      onlyTableData: [],
      // 图片预览的显示框
      previewVisible: false,
      //保存预览图片的url地址
      previewPath: "",
      // 设置请求头
      headerObj: { Authorization: window.localStorage.getItem("token_ds") }
    };
  },
  methods: {
    // 获取商品分类
    async getCategoriesList() {
      const { data: res } = await this.$http.get("categories");
      if (res.meta.status == 200) {
        this.GoodsCategories = res.data;
      }
    },
    // 切换tab导航
    async handleClick(tab, event) {
      if (this.activeName === "1") {
        // 请求动态参数列表====参数
        const { data: res } = await this.$http.get(
          `categories/${this.cateId}/attributes`,
          {
            params: { sel: "many" }
          }
        );
        res.data.forEach(item => {
          item.attr_vals =
            item.attr_vals.length === 0 ? [] : item.attr_vals.trim().split(" ");
        });
        this.manyTableData = res.data;
      } else if (this.activeName === "2") {
        // 请求静态属性列表===属性
        const { data: res } = await this.$http.get(
          `categories/${this.cateId}/attributes`,
          {
            params: { sel: "only" }
          }
        );
        res.data.forEach(item => {
          item.attr_vals =
            item.attr_vals.length === 0 ? [] : item.attr_vals.trim().split(" ");
        });
        this.onlyTableData = res.data;
      }
    },
    // 赋值选中的商品分类--数组
    handleChange(e) {
      // 赋值选中的商品分类--数组
      this.selectCateKey = e;
      this.addgoodsForm.goods_cat = this.selectCateKey.join(",");
    },
    // tabs导航切换时返回
    beforeToleave(activeName, oldActiveName) {
      if (this.selectCateKey.length !== 3) {
        this.$message.error("请选择商品的分类");
        return false;
      }

      //判断是否输入商品名称 ===没有选。则不允许点击;
      // if (this.addgoodsForm.goods_name.trim() == "") {
      //   this.$message.error("请输入商品的名称！");
      //   return false;
      // }
      // //判断是否输入商品价格===没有选。则不允许点击;
      // else if (this.addgoodsForm.goods_price.trim() == "") {
      //   this.$message.error("请输入商品的价格！");
      //   return false;
      // }
      // //判断是否输入商品重量===没有选。则不允许点击;
      // else if (this.addgoodsForm.goods_number.trim() == "") {
      //   this.$message.error("请输入商品的重量！");
      //   return false;
      // }
      // //判断是否输入商品数量===没有选。则不允许点击;
      // else if (this.addgoodsForm.goods_weight.trim() == "") {
      //   this.$message.error("请输入商品的数量！");
      //   return false;
      // }
      // //  判断是否选择了商品参数===没有选。则不允许点击
      // else if (this.selectCateKey.length !== 3) {
      //   this.$message.error("请选择商品的分类");
      //   return false;
      // }
    },
    // 点击文件列表中已上传的文件时的钩子===处理点击预览
    handlePreview(file) {
      // 获取要删除的图片地址。
      this.previewPath =
        "http://www.klxin.cn:8888/" + file.response.data.tmp_path;
      // 显示弹框
      this.previewVisible = true;
    },
    // 文件列表移除文件时的钩子===删除上传额图片
    handleRemove(file) {
      // 获取要删除的图片地址。然后找到addForm表单的pics数组中删除对应的
      const i = this.addgoodsForm.uplaedPic.findIndex(
        item => item.pic === file.response.data.tmp_path
      );
      // 删除
      this.addgoodsForm.uplaedPic.splice(i, 1);
    },
    // 关闭弹框
    closepreviewVisible() {
      this.previewPath = "";
    },
    // 文件上传成功时的钩子===将服务器返回的地址保存
    handlesuccess(response) {
      //将服务器返回的临时路径保存到addForm表单的pics数组中
      this.addgoodsForm.uplaedPic.push({ pic: response.data.tmp_path });
    },
    // 最终的添加商品按钮点击事件
    addGoods() {
      // 进行数据的校验;
      this.$refs.addgoodsRef.validate(async valid => {
        if (!valid) return this.$message.error("清除如基本内容必填项！");
        // 进行数据的整理---将数据进行深拷贝---避免goods_cat数组转换字符串之后导致级联选择器报错
      
        // console.log(form);
        //将goods_cat从数组转换为"1,2,3"字符串形式
        // form.goods_cat = form.goods_cat.join(",");
        //处理attrs数组，数组中需要包含商品的动态参数和静态属性
        //将manyTableData（动态参数）处理添加到attrs
        form.attrs = [];
        this.manyTableData.forEach(item => {
          form.attrs.push({
            attr_id: item.attr_id,
            attr_value:
              item.attr_vals.length === 0 ? "" : item.attr_vals.join(",")
          });
        });

        //将onlyTableData（静态属性）处理添加到attrs
        this.onlyTableData.forEach(item => {
          form.attrs.push({
            attr_id: item.attr_id,
            attr_value:
              item.attr_vals.length === 0 ? "" : item.attr_vals.join(",")
          });
        });
        //发送请求完成商品的添加,商品名称必须是唯一的
        const { data: res } = await this.$http.post(`/goods`, form);
        if (res.meta.status != 201) return this.$message.error("添加商品失败");
        this.$message.success("添加商品成功");
        //编程式导航跳转到商品列表
        this.$router.push("/goods");
      });
    }
  },
  created() {
    this.getCategoriesList();
  },
  filters: {
    toNumber(value) {
      return Number(value);
    }
  },
  computed: {
    cateId() {
      if (this.selectCateKey.length === 3) {
        return this.selectCateKey[2];
      } else {
        return null;
      }
    }
  }
};
</script>
<style lang='less' scoped>
.addGoods {
  width: 100%;
  height: 100%;
  .content {
    margin-top: 10px;
    .el-steps {
      margin-top: 10px;
    }
    /deep/.el-step__title {
      font-size: 12px;
    }
    .addGoodsContent {
      margin-top: 20px;
    }
    .previewImg {
      width: 400px;
      margin: 0 auto;
    }

    //给添加商品按钮添加间距
    .btnAdd {
      margin-top: 15px;
    }
  }
}
</style>